package com.ydd.network.mina;

import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.HandlerThread;
import android.os.IBinder;
import android.support.annotation.IntDef;
import android.support.annotation.Nullable;

import com.ydd.network.mina.ConnectionConfig;
import com.ydd.network.mina.ConnectionManager;

/**
 * Created by tao on 17-3-23.
 */

public class MinaService extends Service {
    private ConnectionThread thread;

    @Override
    public void onCreate() {
        super.onCreate();
        thread = new ConnectionThread("mina", getApplicationContext());
        thread.start();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        return super.onStartCommand(intent, flags, startId);
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        thread.disConnect();
        thread = null;
    }

    class ConnectionThread extends HandlerThread {

        private boolean mIsConnection;
        private ConnectionManager mManager;

        public ConnectionThread(String name, Context context) {
            super(name);
            ConnectionConfig config = new ConnectionConfig.Builder(context)
                    .setIp("192.168.43.8")
                    .setPort(9124)
                    .setReadBUfferSize(10240)
                    .setConnectionTimeout(10000).builder();
            mManager = new ConnectionManager(config);
        }



        /**
         * 开始连接服务器
         */
        @Override
        protected void onLooperPrepared() {
            super.onLooperPrepared();
            for (; ; ) {
                mIsConnection = mManager.connect();
                if (mIsConnection) {
                    break;
                }
                try {
                    Thread.sleep(3000);

                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }

        }

        public void disConnect() {
            mManager.disConnect();
        }

    }
}
